<template>
  <div class="reception-carousel">
    <el-card class="carousel-container">
      <template #header>
        <div class="card-header">
          <span>前台轮播图管理</span>
          <el-button type="primary" @click="handleAdd">
            <el-icon><Plus /></el-icon>
            添加轮播图
          </el-button>
        </div>
      </template>
      
      <div class="carousel-content">
        <el-alert
          title="轮播图管理功能"
          description="这里可以管理前台展示的轮播图内容，包括添加、编辑、删除轮播图等操作。轮播图将显示在系统首页的走马灯区域。"
          type="info"
          show-icon
          :closable="false"
        />
        
        <!-- 轮播图列表 -->
        <div class="carousel-list">
          <el-table :data="carouselList" style="width: 100%">
            <el-table-column prop="id" label="ID" width="80" />
            <el-table-column label="轮播图" width="120">
              <template #default="{ row }">
                <el-image
                  :src="row.imageUrl"
                  :preview-src-list="[row.imageUrl]"
                  fit="cover"
                  style="width: 100px; height: 60px; border-radius: 4px;"
                />
              </template>
            </el-table-column>
            <el-table-column prop="title" label="标题" />
            <el-table-column prop="description" label="描述" show-overflow-tooltip />
            <el-table-column prop="linkUrl" label="跳转链接" show-overflow-tooltip />
            <el-table-column prop="sortOrder" label="排序" width="80" />
            <el-table-column prop="status" label="状态" width="100">
              <template #default="{ row }">
                <el-tag :type="row.status === 'active' ? 'success' : 'info'">
                  {{ row.status === 'active' ? '启用' : '禁用' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="createTime" label="创建时间" width="180" />
            <el-table-column label="操作" width="200" fixed="right">
              <template #default="{ row }">
                <el-button size="small" @click="handleEdit(row)">编辑</el-button>
                <el-button 
                  size="small" 
                  :type="row.status === 'active' ? 'warning' : 'success'"
                  @click="handleToggleStatus(row)"
                >
                  {{ row.status === 'active' ? '禁用' : '启用' }}
                </el-button>
                <el-button size="small" type="danger" @click="handleDelete(row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
        
        <!-- 分页 -->
        <div class="pagination-container">
          <el-pagination
            v-model:current-page="pagination.current"
            v-model:page-size="pagination.size"
            :page-sizes="[10, 20, 50, 100]"
            :total="pagination.total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </el-card>

    <!-- 添加/编辑轮播图对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '添加轮播图' : '编辑轮播图'"
      width="600px"
      :before-close="handleClose"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="100px"
        style="max-width: 500px;"
      >
        <el-form-item label="轮播图标题" prop="title">
          <el-input v-model="formData.title" placeholder="请输入轮播图标题" />
        </el-form-item>
        
        <el-form-item label="轮播图描述" prop="description">
          <el-input
            v-model="formData.description"
            type="textarea"
            :rows="3"
            placeholder="请输入轮播图描述"
          />
        </el-form-item>
        
        <el-form-item label="跳转链接" prop="linkUrl">
          <el-input v-model="formData.linkUrl" placeholder="请输入跳转链接（可选）" />
        </el-form-item>
        
        <el-form-item label="轮播图图片" prop="imageUrl">
          <el-upload
            class="avatar-uploader"
            action="#"
            :show-file-list="false"
            :before-upload="beforeUpload"
            :http-request="handleUpload"
          >
            <img v-if="formData.imageUrl" :src="formData.imageUrl" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
          <div class="upload-tip">点击上传轮播图图片，建议尺寸：1920x600px</div>
        </el-form-item>
        
        <el-form-item label="排序" prop="sortOrder">
          <el-input-number
            v-model="formData.sortOrder"
            :min="1"
            :max="100"
            controls-position="right"
          />
        </el-form-item>
        
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="formData.status">
            <el-radio label="active">启用</el-radio>
            <el-radio label="inactive">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleClose">取消</el-button>
          <el-button type="primary" @click="handleSubmit" :loading="loading">
            {{ dialogType === 'add' ? '添加' : '保存' }}
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'

// 轮播图数据
const carouselList = ref([])

// 分页配置
const pagination = reactive({
  current: 1,
  size: 10,
  total: 0
})

// 对话框相关
const dialogVisible = ref(false)
const dialogType = ref('add')
const loading = ref(false)
const formRef = ref()
const formData = reactive({
  id: null,
  title: '',
  description: '',
  imageUrl: '',
  linkUrl: '',
  sortOrder: 1,
  status: 'active'
})

// 表单验证规则
const formRules = reactive({
  title: [
    { required: true, message: '请输入轮播图标题', trigger: 'blur' }
  ],
  description: [
    { required: true, message: '请输入轮播图描述', trigger: 'blur' }
  ],
  imageUrl: [
    { required: true, message: '请上传轮播图图片', trigger: 'change' }
  ],
  sortOrder: [
    { required: true, message: '请输入排序值', trigger: 'blur' }
  ]
})

// 加载轮播图数据
const loadCarouselData = async () => {
  try {
    // 模拟加载数据 - 这里应该调用后端API
    carouselList.value = [
      {
        id: 1,
        title: '国庆节活动',
        description: '庆祝国庆节特别活动',
        imageUrl: '/carousel/national_day.jpg',
        linkUrl: '/announcement/1',
        sortOrder: 1,
        status: 'active',
        createTime: '2024-10-01 10:00:00'
      },
      {
        id: 2,
        title: '健康讲座',
        description: '秋季健康养生讲座通知',
        imageUrl: '/carousel/health_lecture.jpg',
        linkUrl: '/announcement/2',
        sortOrder: 2,
        status: 'active',
        createTime: '2024-10-02 14:30:00'
      },
      {
        id: 3,
        title: '消防安全',
        description: '消防安全演练通知',
        imageUrl: '/carousel/fire_drill.jpg',
        linkUrl: '/announcement/3',
        sortOrder: 3,
        status: 'inactive',
        createTime: '2024-10-03 09:15:00'
      }
    ]
    pagination.total = carouselList.value.length
    ElMessage.success('轮播图数据加载成功')
  } catch (error) {
    ElMessage.error('加载轮播图数据失败')
  }
}

// 添加轮播图
const handleAdd = () => {
  dialogType.value = 'add'
  resetForm()
  dialogVisible.value = true
}

// 编辑轮播图
const handleEdit = (row) => {
  dialogType.value = 'edit'
  Object.assign(formData, row)
  dialogVisible.value = true
}

// 切换状态
const handleToggleStatus = async (row) => {
  try {
    const newStatus = row.status === 'active' ? 'inactive' : 'active'
    // 这里应该调用后端API更新状态
    row.status = newStatus
    ElMessage.success(`已${newStatus === 'active' ? '启用' : '禁用'}轮播图`)
  } catch (error) {
    ElMessage.error('操作失败')
  }
}

// 删除轮播图
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除轮播图"${row.title}"吗？`,
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 这里应该调用后端API删除数据
    const index = carouselList.value.findIndex(item => item.id === row.id)
    if (index !== -1) {
      carouselList.value.splice(index, 1)
      pagination.total = carouselList.value.length
      ElMessage.success('删除成功')
    }
  } catch (error) {
    // 用户取消删除
  }
}

// 重置表单
const resetForm = () => {
  Object.assign(formData, {
    id: null,
    title: '',
    description: '',
    imageUrl: '',
    linkUrl: '',
    sortOrder: 1,
    status: 'active'
  })
  if (formRef.value) {
    formRef.value.clearValidate()
  }
}

// 关闭对话框
const handleClose = () => {
  dialogVisible.value = false
  resetForm()
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    loading.value = true
    
    // 这里应该调用后端API保存数据
    if (dialogType.value === 'add') {
      // 模拟添加操作
      const newItem = {
        ...formData,
        id: Date.now(),
        createTime: new Date().toLocaleString()
      }
      carouselList.value.unshift(newItem)
      pagination.total = carouselList.value.length
      ElMessage.success('添加成功')
    } else {
      // 模拟编辑操作
      const index = carouselList.value.findIndex(item => item.id === formData.id)
      if (index !== -1) {
        carouselList.value[index] = { ...formData }
        ElMessage.success('更新成功')
      }
    }
    
    dialogVisible.value = false
    resetForm()
  } catch (error) {
    ElMessage.error('表单验证失败')
  } finally {
    loading.value = false
  }
}

// 文件上传前检查
const beforeUpload = (file) => {
  const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isJPG) {
    ElMessage.error('上传图片只能是 JPG/PNG 格式!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('上传图片大小不能超过 2MB!')
    return false
  }
  return true
}

// 处理文件上传
const handleUpload = (options) => {
  const { file } = options
  // 模拟上传成功
  const reader = new FileReader()
  reader.onload = (e) => {
    formData.imageUrl = e.target.result
    ElMessage.success('图片上传成功')
  }
  reader.readAsDataURL(file)
}

// 分页相关
const handleSizeChange = (size) => {
  pagination.size = size
  loadCarouselData()
}

const handleCurrentChange = (current) => {
  pagination.current = current
  loadCarouselData()
}

onMounted(() => {
  loadCarouselData()
})
</script>

<style scoped>
.reception-carousel {
  padding: 20px;
}

.carousel-container {
  min-height: 500px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.carousel-content {
  margin-top: 20px;
}

.carousel-list {
  margin-top: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.avatar-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: border-color 0.3s;
  width: 178px;
  height: 100px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.avatar-uploader:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
}

.avatar {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.upload-tip {
  margin-top: 8px;
  color: #909399;
  font-size: 12px;
}
</style>
